<!--
 * @Descripttion: (总成/set_product)
 * @version: (1.0)
 * @Author: (admin)
 * @Date: (2022-12-01)
 * @LastEditors: (admin)
 * @LastEditTime: (2022-12-01)
-->
<template>
  <div class="app-container">
    <!-- :model属性用于表单验证使用 比如下面的el-form-item 的 prop属性用于对表单值进行验证操作 -->
    <el-form :model="queryParams" size="small" label-position="right" inline ref="queryForm" :label-width="labelWidth" v-show="showSearch" 
      @submit.native.prevent>
          				    
      <el-form-item label="总成件号" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入总成件号" />
      </el-form-item>
    				    
      <el-form-item label="总成名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入总成名称" />
      </el-form-item>
    				    
      <el-form-item label="总成大类" prop="productCatalog">
        <el-select v-model="queryParams.productCatalog" placeholder="请选择总成大类">
          <el-option v-for="item in productCatalogOptions" :key="item.productCatalogCode" :label="item.productCatalogName" :value="item.productCatalogCode"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['set:product:add']" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" :disabled="single" v-hasPermi="['set:product:edit']" plain icon="el-icon-edit" size="mini" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" :disabled="multiple" v-hasPermi="['set:product:remove']" plain icon="el-icon-delete" size="mini" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
            <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['set:product:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['set:product:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据区域 -->
    <el-table :data="dataList" v-loading="loading" ref="table" border highlight-current-row @sort-change="sortChange" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column prop="productCode" label="总成件号" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="productName" label="总成名称" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="printDescribe" label="打印描述" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="innerCode" label="内部件号" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="productCatalog" label="总成大类" align="center">
      </el-table-column>
      <el-table-column prop="ispart" label="总成类型" align="center" :formatter="ispartFormat" />
      <el-table-column prop="gsk" label="GSK" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="lfd" label="LFD" align="center" :show-overflow-tooltip="true" />

      <el-table-column label="操作" align="center" width="140">
        <template slot-scope="scope">
          <el-button size="mini" v-hasPermi="['set:product:edit']" type="success" icon="el-icon-edit" title="编辑" 
            @click="handleUpdate(scope.row)"></el-button>      
          <el-button size="mini" v-hasPermi="['set:product:remove']" type="danger" icon="el-icon-delete" title="删除" 
            @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination class="mt10" background :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改总成对话框 -->
    <el-dialog :title="title" :lock-scroll="false" :visible.sync="open" >
      <el-form ref="form" :model="form" :rules="rules" :label-width="formLabelWidth">
        <el-row :gutter="20">
          <el-col :lg="12">
            <el-form-item label="总成件号" prop="productCode">
              <el-input v-model="form.productCode" placeholder="请输入总成件号" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="总成名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入总成名称" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="打印描述" prop="printDescribe">
              <el-input v-model="form.printDescribe" placeholder="请输入打印描述" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="内部件号" prop="innerCode">
              <el-input v-model="form.innerCode" placeholder="请输入内部件号" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="总成大类" prop="productCatalog">
              <el-select v-model="form.productCatalog" placeholder="请选择总成大类">
                <el-option v-for="item in productCatalogOptions" :key="item.productCatalogCode" :label="item.productCatalogName" :value="item.productCatalogCode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
    
          <el-col :lg="12">
            <el-form-item label="总成类型" prop="ispart">
              <el-select v-model="form.ispart" placeholder="请选择总成类型">
                <el-option v-for="item in ispartOptions" :key="item.dictValue" :label="item.dictLabel" :value="parseInt(item.dictValue)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="GSK" prop="gsk">
              <el-input v-model="form.gsk" placeholder="请输入GSK" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="LFD" prop="lfd">
              <el-input v-model="form.lfd" placeholder="请输入LFD" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
 <!-- 总成导入对话框 -->
 <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的总成数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { 
  listproduct,
  addproduct,
  delproduct,
  updateproduct,
  getproduct,
  importTemplate,
  exportproduct,
} from '@/api/parameter/set_product.js';
import { 
  listAllproductCatalog,
} from '@/api/parameter/set_product_catalog.js';
import { getToken } from "@/utils/auth";
export default {
  name: "product",
  data() {
    return {
      // 总成导入参数
      upload: {
        // 是否显示弹出层（总成导入）
        open: false,
        // 弹出层标题（总成导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的总成数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      labelWidth: "100px",
      formLabelWidth:"100px",
      // 选中id数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sort: undefined,
        sortType: undefined,
        productCode: undefined,
        productName: undefined,
        productCatalog: undefined,
      },
      // 弹出层标题
      title: "",
      // 操作类型 1、add 2、edit
      opertype: 0,
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      columns: [
        { index: 0, key: 'id', label: ``, checked:  true  },
        { index: 1, key: 'bomId', label: ``, checked:  true  },
        { index: 2, key: 'productCode', label: `总成件号`, checked:  true  },
        { index: 3, key: 'productName', label: `总成名称`, checked:  true  },
        { index: 4, key: 'printDescribe', label: `打印描述`, checked:  true  },
        { index: 5, key: 'innerCode', label: `内部件号`, checked:  true  },
        { index: 6, key: 'productCatalog', label: `总成大类`, checked:  true  },
        { index: 7, key: 'ispart', label: `总成类型`, checked:  true  },
        { index: 8, key: 'gsk', label: `GSK`, checked:  true  },
        { index: 9, key: 'lfd', label: `LFD`, checked:  false  },
        { index: 10, key: 'createBy', label: `创建者`, checked:  false  },
        { index: 11, key: 'createTime', label: `创建时间`, checked:  false  },
        { index: 12, key: 'updateBy', label: `更新者`, checked:  false  },
        { index: 13, key: 'updateTime', label: `更新时间`, checked:  false  },
        { index: 14, key: 'remark', label: `备注`, checked:  false  },
        { index: 15, key: 'status', label: ``, checked:  false  },
      ],
      // 总成大类选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
      productCatalogOptions: [],
      // 总成类型选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
      ispartOptions: [],
      // 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
      statusOptions: [],
      // 数据列表
      dataList: [],
      // 总记录数
      total: 0,
      // 提交按钮是否显示
      btnSubmitVisible: true,
      // 表单校验
      rules: {
        productCode: [
          { required: true, message: "总成件号不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "总成名称不能为空", trigger: "blur" }
        ],
        productCatalog: [
          { required: true, message: "总成大类不能为空", trigger: "change" }
        ],
        ispart: [
          { required: true, message: "总成类型不能为空", trigger: "change" }
        ],
      },
    };
  },
  created() {    
    // 列表数据查询
    this.getList();
    this.getDropDownProductCatalogList();
    this.getDicts("mes_product_catalogcode_type").then(response => {
      this.ispartOptions = response.data;
    });
  },
  methods: {
    getDropDownProductCatalogList(){
      listAllproductCatalog().then(res => {
        if (res.code == 200) {
           this.productCatalogOptions = res.data;
        }
       })
    },
     /** 导入按钮操作 */
     handleImport() {
      this.upload.title = "总成导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 查询数据
    getList() {
      this.loading = true;
      listproduct(this.queryParams).then(res => {
         if (res.code == 200) {
           this.dataList = res.rows;
        this.total = res.total;
           this.loading = false;
         }
       })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 重置数据表单
    reset() {
      this.form = {
        productCode: undefined,
        productName: undefined,
        printDescribe: undefined,
        innerCode: undefined,
        productCatalog: undefined,
        ispart: undefined,
        gsk: undefined,
        lfd: undefined,
      };
      this.resetForm("form");
    },
    // 重置查询操作
    resetQuery() {
      this.timeRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1
      this.multiple = !selection.length;
    },
     // 自定义排序
    sortChange(column) {
      if (column.prop == null || column.order == null) {
        this.queryParams.sort = undefined;
        this.queryParams.sortType = undefined;
      } else {
        this.queryParams.sort = column.prop;
        this.queryParams.sortType = column.order;
      }

      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
      this.opertype = 1;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;

      this.$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？')
        .then(function () {
          return delproduct(Ids);
        })
        .then(() => {
          this.handleQuery();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getproduct(id).then((res) => {
        const { code, data } = res;
        if (code == 200) {
          this.open = true;
          this.title = "修改数据";
          this.opertype = 2;

          this.form = {
            ...data,
          };
        }
      });
    },
    // 总成大类字典翻译
    productCatalogFormat(row, column) {
      return this.selectDictLabel(this.productCatalogOptions, row.productCatalog);
    },
    // 总成类型字典翻译
    ispartFormat(row, column) {
      return this.selectDictLabel(this.ispartOptions, row.ispart);
    },
    // 字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log(JSON.stringify(this.form));
          this.form.ispart=parseInt(this.form.ispart);
          if (this.form.id != undefined && this.opertype === 2) {
            updateproduct(this.form)
              .then((res) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
            })
            .catch((err) => {
                //TODO 错误逻辑
              });
          } else {
            addproduct(this.form)
              .then((res) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
            })
            .catch((err) => {
                //TODO 错误逻辑
              });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有总成数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportproduct(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>